package com.baidu.location.demo;

import static com.baidu.location.demo.MainActivity.user;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.content.ClipData;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.entity.Authority;
import com.entity.File;
import com.entity.Login;
import com.entity.Response;
import com.entity.User;
import com.util.FileUtil;
import com.util.HttpUtils;
import com.util.UploadHelper;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

public class CreateuserActivity extends AppCompatActivity {
    private Button returnLogin;
    private Button registerGo;
    private EditText createuserNumber;
    private EditText createname;
    private EditText createpassWord;
    private EditText createsignature;
    private ImageView createheadPortrait;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_createuser);
        returnLogin=findViewById(R.id.returnLogin);
        registerGo=findViewById(R.id.registerGo);
        createsignature=findViewById(R.id.createsignature);
        createheadPortrait=findViewById(R.id.createheadPortrait);
        createpassWord=findViewById(R.id.createpassWord);
        createname=findViewById(R.id.createname);
        createuserNumber=findViewById(R.id.createuserNumber);
        returnLogin.setOnClickListener(view -> {
            finish();
        });
        createheadPortrait.setOnClickListener(new View.OnClickListener() {
            @SuppressLint("IntentReset")
            @Override
            public void onClick(View view) {
                Intent intent =new Intent();
                intent.setType("image/*");
                intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE,false);
                intent.setAction(Intent.ACTION_GET_CONTENT);
                intent.setAction(Intent.ACTION_PICK);
                intent.setData(MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(Intent.createChooser(intent,"Select Picture"),200);
            }
        });
        registerGo.setOnClickListener(view -> {
            User user=new User();
            user.setUserNumber(createuserNumber.getText().toString());
            user.setName(createname.getText().toString());
            user.setPassWord(createpassWord.getText().toString());
            user.setSignature(createsignature.getText().toString());
//            user.setHeadPortrait(createname.getText().toString());
            if(user.getName().isEmpty()){
                Toast.makeText(CreateuserActivity.this,"用户名不能为空",Toast.LENGTH_LONG).show();
                return;
            }
            if(user.getPassWord().isEmpty()){
                Toast.makeText(CreateuserActivity.this,"密码不能为空",Toast.LENGTH_LONG).show();
                return;
            }else if(user.getPassWord().length()<5){
                Toast.makeText(CreateuserActivity.this,"密码长度不能小于五位",Toast.LENGTH_LONG).show();
                return;
            }
            if(user.getUserNumber().isEmpty()){
                Toast.makeText(CreateuserActivity.this,"账号不能为空",Toast.LENGTH_LONG).show();
                return;
            }else if(user.getUserNumber().length()<5){
                Toast.makeText(CreateuserActivity.this,"账号长度不能小于五位",Toast.LENGTH_LONG).show();
                return;
            }
            createheadPortrait.buildDrawingCache(true);
            createheadPortrait.buildDrawingCache();
            Bitmap image= createheadPortrait.getDrawingCache();
            ByteArrayOutputStream baos=new  ByteArrayOutputStream();
            image.compress(Bitmap.CompressFormat.PNG,100, baos);
            new Thread(){
                @Override
                public void run() {
                    super.run();
                    String data=new UploadHelper().upload(baos.toByteArray());
                    if(!data.isEmpty()){
                        Response<File> file= JSONObject.parseObject(data,new TypeReference<Response<File>>(){});
                        if(file.getStatusCode()==200){
                            user.setHeadPortrait(file.getValue().getPath());
                            user.setHeadPortraitKey(file.getValue().getKey());
                            Response<String> encrypt=JSONObject.parseObject(HttpUtils.Get("Util/MD5Encrypt?data="+user.getPassWord()),new TypeReference<Response<String>>(){});
                            user.setPassWord(encrypt.getValue());
                            String userJson= HttpUtils.Post("Consumer/CreateConsumer", JSON.toJSONString(user));
                            Response<String>userId = JSONObject.parseObject(userJson,new TypeReference<Response<String>>(){});
                            if(userId.getStatusCode()==200){
                                Response<Login> users= JSONObject.parseObject(HttpUtils.Post("Login/Login?user="+user.getUserNumber()+"&pass="+encrypt.getValue(),""),new TypeReference<Response<Login>>(){});
                                if(users.getStatusCode()==200){
                                    Authority.setAuthorization(users.getValue().getToken());
                                    try {
                                        FileUtil.Save(CreateuserActivity.this,"user.json",JSONObject.toJSONString(users.getValue().getUser()));
                                    } catch (IOException e) {
                                        e.printStackTrace();
                                    }
                                    Intent i=new Intent(CreateuserActivity.this,MainActivity.class);
                                    i.putExtra("user", JSON.toJSONString(users.getValue().getUser()));
                                    (CreateuserActivity.this).runOnUiThread(() -> startActivity(i));
                                }else{
                                    CreateuserActivity.this.runOnUiThread(() -> Toast.makeText(CreateuserActivity.this, users.getMessage(),Toast.LENGTH_LONG).show());
                                }
                            }
                        }else{
                            CreateuserActivity.this.runOnUiThread(() -> Toast.makeText(CreateuserActivity.this,file.getMessage(),Toast.LENGTH_LONG).show());
                        }
                    }
                }
            }.start();
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==200&&data!=null){
            new Thread(){
                @Override
                public void run() {
                    super.run();
                    Uri uri= data.getData();
                    if(uri!=null){
                        (CreateuserActivity.this).runOnUiThread(() -> createheadPortrait.setImageURI(uri));
                    }
                }
            }.start();
        }
    }
}